﻿CREATE PROCEDURE [dbo].[DefekturaCategoriesInsert]
(
	@Name varchar(50),
	@MinPeekValForPeriod real,
	@MaxPeekValForPeriod real,
	@PrblCode real,
	@Note varchar(250),
	@MD datetime,
	@MW varchar(50)
)
AS
DECLARE @strMsg nvarchar(500), @intRet int, @intErrCode int
DECLARE @intNextId int
	SET NOCOUNT ON

IF (@Name Is Null)
BEGIN
	SELECT @intErrCode = 1, @strMsg = 'Неправильные параметры в вызове процедуры ' + Object_Name(@@Procid) + ' !'
	RAISERROR (@strMsg, 11, @intErrCode)
	RETURN @intErrCode
END

IF ltrim(@Name) = ''
BEGIN
	SELECT @intErrCode = 2, @strMsg = 'Незаполнено наименование!'
	RAISERROR (@strMsg, 11, @intErrCode)
	RETURN @intErrCode
END

IF EXISTS (SELECT TOP 1 ID FROM CO.DefekturaCategories WHERE Name = @Name AND ToDelete = 0 )
BEGIN
	SELECT @intErrCode = 3, @strMsg = 'Дублируется наименование!'
	RAISERROR (@strMsg, 11, @intErrCode)
	RETURN @intErrCode
END

IF NOT EXISTS (SELECT DepartmentId FROM PR.DepartmentOptions WHERE DepartmentId = 0 ) 
BEGIN
	SELECT @intErrCode = 4, @strMsg = 'Изменять данные спрвочников можно только в офисе!'
	RAISERROR (@strMsg, 11, @intErrCode)
	RETURN @intErrCode
END

EXEC [dbo].[ProcessStatistic] @Note OUTPUT, @MD OUTPUT, @MW OUTPUT
--получение значения идентификатора
EXEC @intRet = dbo.GetNextCounterFor 'Common', @intNextId OUTPUT
IF @intRet <> 0 RETURN @intRet

	SET NOCOUNT OFF;

INSERT INTO CO.DefekturaCategories 
( Id, [Name], MinPeekValForPeriod, MaxPeekValForPeriod, PrblCode, [Note], [MD], [MW]) 
VALUES ( @intNextId, @Name, @MinPeekValForPeriod, @MaxPeekValForPeriod, @PrblCode, @Note, @MD, @MW);
	
SELECT Id, [Name], MinPeekValForPeriod, MaxPeekValForPeriod, PrblCode, Note, MD, MW 
FROM CO.DefekturaCategories WHERE (Id = @intNextId)

RETURN 0

